package org.ch02.test00.demo07.teacherWork;

import org.ch02.entity.Student;

import java.lang.reflect.Array;
import java.lang.reflect.Field;

/**
 * @author CSY
 * @date 2025 - 03 - 20
 */
public class MainTest {
    public static void main(String[] args) throws Exception {
        //创建一个用于存储Student对象 的一维数组
        Object arr = Array.newInstance(Student.class, 2);
        //获取操作类的Class对象
        Class<Student> clazz = Student.class;
        //实例化
        Student stu1 = clazz.getConstructor().newInstance();

        //获取Student类的字段对象
        Field nameField = clazz.getDeclaredField("name");
        Field ageField = clazz.getDeclaredField("age");
        Field weightField = clazz.getDeclaredField("weight");

        //开启字段权限
        nameField.setAccessible(true);
        ageField.setAccessible(true);
        weightField.setAccessible(true);

        //设置字段值
        nameField.set(stu1,"张三");
        ageField.set(stu1,20);
        weightField.set(stu1,65.5f);

        //使用构造方法实例化Student对象
        Student stu2 = clazz.getConstructor(String.class, int.class, Double.class).newInstance("李四", 18, 120d);

        //使用Array的方法将两个Student对象存入反射的数组中
        Array.set(arr,0,stu1);
        Array.set(arr,1,stu2);

        //使用转换的方式循环输出
        /*if(arr instanceof Student[]){
            Student[] stuArr = (Student[]) arr;
            for(Student stu : stuArr){
                System.out.println(stu);
            }
        }*/

        //使用Array的方法进行循环输出
        for (int i = 0; i < Array.getLength(arr); i++) {
            System.out.println(Array.get(arr, i));
        }
    }
}
